<template>
  <div class="login">
      <div class="login-content">
        <h1>Vue-Admin</h1>
        <el-form :model="form" :rules="rules" v-loading="loading" ref="loginForm">
          <el-form-item prop="username">
            <el-input prefix-icon="user" v-model="form.username" placeholder="Please input" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="lock" type="password" v-model="form.password" placeholder="Please input password" show-password />
          </el-form-item>
          <el-form-item >
            <el-button type="primary" @click="login" class="login-btn">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {ElNotification} from "element-plus";
import {useRouter} from "vue-router";
import {toLogin} from "@/api/user.js";

const form = reactive({
  username: '',
  password: ''
})
const loginForm = ref()
const loading = ref(false)
const router = useRouter();
const validateUsername = (rule, value, callback) => {
  if (value.length === 0) {
    callback(new Error('请输入用户名'))
  } else {
    callback()
  }
}
const validatePass = (rule, value, callback) => {
  if (value.length < 6 && value.length > 16) {
    callback(new Error('密码在6到16位之间'))
  } else {
    callback()
  }
}
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
})
const login = async () => {
  await loginForm.value.validate()
  loading.value = true

  try {
    const res = await toLogin({account: form.username, password: form.password})
    if (res.code === '000') {
      await router.push('/home')
      console.log(res.data)
      localStorage.setItem('web-auth-plat', JSON.stringify(res.data))
      ElNotification({
        type: 'success',
        message: res.msg,
        title: `Hi, 你好`,
      })
      loading.value = false
    }else {
      loading.value = false
      ElNotification({
        type: 'error',
        message: res.msg,
      })
    }
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: error.msg,
    })
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  background: #909399;
  .login-content {
    width: 400px;
    padding-top: 200px;
    margin: 0 auto;
    h1 {
      text-align: center;
      font-size: 1.5rem;
      line-height: 2rem;
      font-weight: 600;
      color: #fff;
      margin-bottom: 20px;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>